const db = require("../db/index");
const bcrypt = require("bcryptjs");

exports.getUserInfo = (req, res) => {
  const sqlStr =
    " select id, username, nickname, email, user_pic from ev_users where id = ?";
  db.query(sqlStr, req.user.id, (err, results) => {
    if (err) return res.cc(err);

    if (results.length !== 1) return res.cc("获取用户信息失败");

    res.send({
      status: 200,
      message: "获取用户信息成功",
      data: results[0],
    });
  });
};

exports.updateUserInfo = (req, res) => {
  const userInfo = req.body;

  const sqlStr = "update ev_users set ? where id = ?";
  db.query(sqlStr, [userInfo, userInfo.id], (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows !== 1) return res.cc("更新失败");
    res.cc("更新成功", 200);
  });
};

// 更新密码
exports.updatePassword = (req, res) => {
  const sql = "select * from ev_users where id = ?";
  db.query(sql, req.user.id, (err, results) => {
    if (err) return res.cc(err);
    if (results.length !== 1) return res.cc("用户不存在");

    //判读用户输入的旧密码是否正确
    const compareResult = bcrypt.compareSync(
      req.body.oldPwd,
      results[0].password
    );
    if (!compareResult) return res.cc("用户密码错误");

    //对新密码进行加密
    const newPwd = bcrypt.hashSync(req.body.newPwd, 10);
    const sql = "update ev_users set password= ?  where id = ? ";
    db.query(sql, [newPwd, req.user.id], (err, results) => {
      if (err) return res.cc(err);
      if (results.affectedRows !== 1) return res.cc("更新失败");

      // token 信息只是加密了除密码以及头像之外的其他信息，所以密码更新了，token不变，仍然可以正常访问此页面
      // 如果更新了其他用户信息，token信息也不发生变化，只和设置的过期时效有关

      res.cc("update password successfully", 0);
    });
  });
};

exports.updateAvatar = (req, res) => {
  const sql = "update ev_users set user_pic = ? where id = ?";
  db.query(sql, [req.body.avatar, req.user.id], (err, results) => {
    if (err) return res.cc(err);
    if (results.affectedRows !== 1) return res.cc("更新用户照片失败");

    res.cc("更新照片成功", 0);
  });
};
